#!/bin/tcsh -ef
####
#
#############################################################################
#                                                                           #
# Title: Mask Crystal from Polygon                                          #
#                                                                           #
# (C) 2dx.org, GNU Plublic License.                                         #
#                                                                           #
# Created..........: 08/20/2006                                             #
# Last Modification: 08/20/2006                                             #
# Author...........: 2dx.org                                                #
#                                                                           #
#############################################################################
#
# SORTORDER: 55
#
# MANUAL: This script assists in manually masking the crystal. 
#
# MANUAL: Use the full-screen browser to manually define a polygon, which will then be saved as <I>selectionList.dat</I>. Input for the manual polygon selection can come from either the raw image itself, the ManualMasking_CCmap.mrc file, or the ManualMasking_UnbendPlot.mrc file.
#
# MANUAL: After having defined a polygon, run this script to mask the image. The area defined in the polygon will be masked with blurred edges. The parameter <I>Masking Fourier Radius</I> defines how blurred the edges are: A larger value means a sharper edge (0...0.5).
#
# DISPLAY: imagename
# DISPLAY: nonmaskimagename
# DISPLAY: imagenumber
# DISPLAY: imagesidelength
# DISPLAY: magnification
# DISPLAY: stepdigitizer
# DISPLAY: lattice
# DISPLAY: secondlattice
# DISPLAY: maska
# DISPLAY: maskb01
# DISPLAY: maskb02
# DISPLAY: maskb03
# DISPLAY: maskb04
# DISPLAY: maskb05
# DISPLAY: tempkeep
# DISPLAY: comment
# DISPLAY: mask_fourmask
#
#$end_local_vars
#
set bin_2dx = ""
set proc_2dx = ""
#
set imagename = ""
set nonmaskimagename = ""
set imagenumber = ""
set imagesidelength = ""
set magnification = ""
set stepdigitizer = ""
set lattice = ""
set secondlattice = ""
set maska = ""
set maskb01 = ""
set maskb02 = ""
set maskb03 = ""
set maskb04 = ""
set maskb05 = ""
set tempkeep = ""
set mask_fourmask = ""
#
#$end_vars
#
echo "<<@progress: 1>>"
#
set mask_reset_reflocation = "n"
# 
set ccp4_setup = 'y'
set IS_2DX = yes
source ${proc_2dx}/initialize
#
set scriptname = 2dx_maskCrystal
\rm -f LOGS/${scriptname}.results
#
set date = `date`
echo date = ${date}
#
set originalpolygon = selectionList.dat
#
set masktobig = `echo ${mask_fourmask} | awk '{ if ( $1 > 0.5 ) { s = 1 } else { s = 0 }} END { print s }'`
if ( ${masktobig} == '1' ) then
  set mask_fourmask = 0.2
  echo "set mask_fourmask = ${mask_fourmask}" >> LOGS/${scriptname}.results
  ${proc_2dx}/linblock "Fourier Mask corrected to ${mask_fourmask}."
endif
#
if ( ${nonmaskimagename} != ${imagename} ) then
  ${proc_2dx}/linblock "Image has been masked before."
  echo "#WARNING: Image has been masked before." >> LOGS/${scriptname}.results
endif
#
echo "# IMAGE: ${nonmaskimagename}.mrc" >> LOGS/${scriptname}.results
echo "# IMAGE: ManualMasking_CCmap.mrc" >> LOGS/${scriptname}.results
echo "# IMAGE: ManualMasking_UnbendPlot.mrc" >> LOGS/${scriptname}.results
echo "# IMAGE: ${originalpolygon} <TXT: Original Polygon File>"  >> LOGS/${scriptname}.results
echo "# IMAGE: SCRATCH/TMPpolygon.dat <TXT: Polygon File>"  >> LOGS/${scriptname}.results
echo "# IMAGE: SCRATCH/TMPcoordinate.dat <TXT: Coordinate File>"  >> LOGS/${scriptname}.results
echo "# IMAGE: SCRATCH/TMPnewimagesidelength.dat <TXT: Polygon File>"  >> LOGS/${scriptname}.results
#
if ( ! -e ${originalpolygon} ) then
  if ( -e ManualMasking_CCmap.mrc ) then
    #############################################################################
    ${proc_2dx}/linblock "${originalpolygon} does not exist."
    ${proc_2dx}/linblock "#"
    echo ":: "
    echo ":: "
    echo "::                         First define a polygon manually,"
    echo ":: "
    echo "::                  using one of the three files in the Images pane"
    echo ":: "
    echo ":: "
    ${proc_2dx}/linblock "#"
    #############################################################################
  else
    ${proc_2dx}/linblock "${originalpolygon} does not exist."
    if ( -e ManualMasking_UnbendPlot.mrc ) then
      ${proc_2dx}/linblock "ManualMasking_CCmap.mrc does not exist."
    else
      ${proc_2dx}/linblock "ManualMasking_CCmap.mrc and ManualMasking_UnbendPlot.mrc do not exist."
    endif
    ${proc_2dx}/linblock "#"
    echo ":: "
    echo "::                         First define a polygon manually."
    echo ":: "
    echo "::          You can do that using the original image (see Images pane), "
    echo "::                or by (re-)running Unbend-II with the option to "
    echo "::        'Create information for manual masking' set to 'yes', and then"
    echo "::   using the ManualMasking_CCmap.mrc or ManualMasking_UnbendPlot.mrc files."
    echo ":: "
    ${proc_2dx}/linblock "#"
    #
  endif
  echo "<<@progress: 100>>"
  #############################################################################
  ${proc_2dx}/linblock "${scriptname} aborting (normal end)"
  #############################################################################
  #
else
  #
  #############################################################################
  ${proc_2dx}/linblock "LABEL - to create flat value=1 file"
  #############################################################################
  #
  ${bin_2dx}/labelh.exe << eot
${nonmaskimagename}.mrc
2               ! Linear OD stretch  ( y = mx + b )
SCRATCH/TMPvalue1.mrc
0.0 1.0
0
eot
  #
  echo "<<@progress: 10>>"
  #
  ##############################################################################
  ${proc_2dx}/linblock "modifypolygon - to prepare the input data for boximage"
  ##############################################################################
  #
  set polygonfile = SCRATCH/TMPpolygon.dat
  set coordinatefile = SCRATCH/TMPcoordinate.dat
  set newimagesidelengthfile = SCRATCH/TMPnewimagesidelength.dat
  set iborder = `echo ${mask_fourmask} | awk '{ s = int( 3.0 / $1 ) } END { print s }'`
  set rfactor = 1.0
  #
  echo "Using as original polygon file:"
  cat ${originalpolygon}
  echo " "
  #
  \rm -f ${polygonfile}
  \rm -f ${coordinatefile}
  \rm -f ${newimagesidelengthfile}
  ${bin_2dx}/2dx_modifypolygon.exe << eot > SCRATCH/TMPmodifypolygon.dat
${originalpolygon}
${polygonfile}
${coordinatefile}
${newimagesidelengthfile}
${imagesidelength}
${rfactor}
${iborder}
eot
  #
  cat SCRATCH/TMPmodifypolygon.dat | sed 's/::/only if cropping= /g' | sed 's/:/only if cropping= /g'
  #
  \rm -f SCRATCH/TMPmodifypolygon.dat
  #
  echo "<<@progress: 15>>"
  #
  #############################################################################
  ${proc_2dx}/linblock "BOXIMAGE - to mask the value=1 file with the polygon"
  #############################################################################
  #
  echo "Using as polygon file:"
  cat ${polygonfile}
  echo " "
  #
  \rm -f SCRATCH/TMPmask1.mrc
  # Center of gravity of polygon goes into this file:
  \rm -f boximage.tmp
  setenv IN  SCRATCH/TMPvalue1.mrc
  setenv OUT SCRATCH/TMPmask1.mrc
  ${bin_2dx}/2dx_boximage.exe  << eot
`cat ${polygonfile}`
eot
  #
  \rm -f ${polygonfile}
  #
  if ( ! -e boximage.tmp ) then
    ${proc_2dx}/protest "ERROR: 2dx_boximage.exe did not produce boximage.tmp"
  endif
  \rm SCRATCH/TMPvalue1.mrc
  #
  echo "<<@progress: 20>>"
  #
  #############################################################################
  ${proc_2dx}/linblock "FFTIR - to calculate Fourier transform"
  #############################################################################
  #
  \rm -f SCRATCH/TMPmask1.fft.mrc
  setenv IN  SCRATCH/TMPmask1.mrc
  setenv OUT SCRATCH/TMPmask1.fft.mrc
  #
  ${bin_2dx}/2dx_fftrans.exe
  #
  \rm SCRATCH/TMPmask1.mrc
  #
  echo "<<@progress: 30>>"
  #
  #############################################################################
  ${proc_2dx}/linblock "MASKTRAN - to get rid of high resolution"
  ${proc_2dx}/linblock "         - using a Fourier radius of ${mask_fourmask}"
  #############################################################################
  #
  \rm -f SCRATCH/TMPmask1.fft.mask.mrc
  setenv IN  SCRATCH/TMPmask1.fft.mrc
  setenv OUT SCRATCH/TMPmask1.fft.mask.mrc
  setenv SPOTS SCRATCH/TMPspot.spt
  #
  echo "0,0"   >  SCRATCH/TMPspot.spt
  #
  set locmask = `echo ${mask_fourmask} ${imagesidelength} | awk '{ s = $1 * $2 / 2 } END { print s }'`
  ${bin_2dx}/2dx_masktrana.exe << eot
2 F T F ! ISHAPE=1(CIRC),2(GAUSCIR),3(RECT)HOLE,IAMPLIMIT(T or F),ISPOT,IFIL
${locmask}       ! RADIUS OF HOLE IF CIRCULAR, X,Y HALF-EDGE-LENGTHS IF RECT.
10000,0,0,10000 -9 9 -9 9 200.0 1 !A/BX/Y,IH/IKMN/MX,RMAX,ITYPE
eot
  #
  \rm SCRATCH/TMPmask1.fft.mrc
  \rm SCRATCH/TMPspot.spt
  #
  echo "<<@progress: 40>>"
  #
  #############################################################################
  ${proc_2dx}/linblock "FFTIR - to calculate Fourier transform"
  #############################################################################
  #
  \rm -f SCRATCH/TMPmask2.mrc
  setenv IN  SCRATCH/TMPmask1.fft.mask.mrc
  setenv OUT SCRATCH/TMPmask2.mrc
  #
  ${bin_2dx}/2dx_fftrans.exe
  #
  \rm SCRATCH/TMPmask1.fft.mask.mrc
  #
  echo "<<@progress: 50>>"
  #
  #############################################################################
  ${proc_2dx}/linblock "LABEL - to level the mask between 0.0 and 1.0"
  #############################################################################
  #
  ${bin_2dx}/labelh.exe << eot
SCRATCH/TMPmask2.mrc
99
3               ! CUT OFF OVER - AND UNDERFLOWS
SCRATCH/TMPmask3.mrc
0.0 1.0
0
eot
  #
  \rm SCRATCH/TMPmask2.mrc
  #
  echo "<<@progress: 60>>"
  #
  #
  #############################################################################
  ${proc_2dx}/linblock "LABEL - to create final masking info as 1024x1024px file"
  #############################################################################
  #
  \rm -f SCRATCH/TMPmask4.mrc
  #
  ${bin_2dx}/labelh.exe << eot
SCRATCH/TMPmask3.mrc
33
SCRATCH/TMPmask4.mrc
1024,1024
eot
  #
  #
  #############################################################################
  ${proc_2dx}/linblock "LABEL - to create final masking info as 1024x1024px file"
  #############################################################################
  #
  \rm -f ${nonmaskimagename}_mask.mrc
  #
  ${bin_2dx}/labelh.exe << eot
SCRATCH/TMPmask4.mrc
-3
${nonmaskimagename}_manualmask.mrc
eot
  #
  echo "# IMAGE: ${nonmaskimagename}_manualmask.mrc <MRC: Making Info File>"  >> LOGS/${scriptname}.results
  #
  #############################################################################
  ${proc_2dx}/linblock "TWOFILE - to multiply image with masking-image"
  #############################################################################
  #
  \rm -f m${nonmaskimagename}.mrc
  setenv IN1 ${nonmaskimagename}.mrc
  setenv IN2 SCRATCH/TMPmask3.mrc
  setenv OUT m${nonmaskimagename}.mrc
  ${bin_2dx}/2dx_twofile.exe << eot
5               ! ICOMB (5 is a new option that amplitude-levels file A with B
0 0 0 0 0 ! IORIGIN,OXA,OYA,OXB,OYB  Origin shifts to FFTs
eot
  #
  if ( ${tempkeep} == 'y' ) then
    \mv -f SCRATCH/TMPmask3.mrc SCRATCH/maskCrystal-mask.mrc
    echo "# IMAGE:" SCRATCH/maskCrystal-mask.mrc  >> LOGS/${scriptname}.results
  else
    \rm SCRATCH/TMPmask3.mrc
  endif
  echo "<<@progress: 90>>"
  #
  echo "# IMAGE: "m${nonmaskimagename}.mrc  >> LOGS/${scriptname}.results
  set oldname = `echo ${imagename}`
  set imagename = `echo m${nonmaskimagename}`
  if ( ${oldname} != ${imagename} ) then
    echo "set imagename = ${imagename}" >> LOGS/${scriptname}.results
    ${proc_2dx}/linblock "Imagename changed from ${oldname} to ${imagename}."
    echo "#WARNING: Imagename changed from ${oldname} to ${imagename}." >> LOGS/${scriptname}.results
  endif
  #
  #
  \rm -f boximage.tmp
  #
  echo "set MASKING_done = y" >> LOGS/${scriptname}.results
  #
  echo "set domask = n" >> LOGS/${scriptname}.results
  #
  echo "set FFT_done = n" >> LOGS/${scriptname}.results
  echo "set UNBENDING_done = n" >> LOGS/${scriptname}.results
  echo "set ML_done = n" >> LOGS/${scriptname}.results
  echo "set CTF_done = n" >> LOGS/${scriptname}.results
  echo "set SPOTS_done = n" >> LOGS/${scriptname}.results
  echo "set use_masked_image = y" >> LOGS/${scriptname}.results
  #
  ${proc_2dx}/linblock "#"
  echo ":: "
  echo ":: Now save the parameters and run again: "
  echo "::                Calculate FFT "
  echo "::                Get SpotList for Unbend I "
  echo "::                Unbend I "
  echo "::                Get SpotList (complete) "
  echo "::                Unbend II "
  echo "::                Correct CTF "
  echo "::                Generate Map "
  echo ":: "
  ${proc_2dx}/linblock "#"
  #
  echo "<<@progress: 100>>"
  ##########################################################################
  ${proc_2dx}/linblock "${scriptname} - normal end."
  ##########################################################################
  #
endif
#
  
